package com.martin.ads.vrlib.filters.vr;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.Matrix;

import com.martin.ads.vrlib.filters.base.PassThroughFilter;
import com.martin.ads.vrlib.object.Plane;
import com.martin.ads.vrlib.textures.RGBTexture;
import com.martin.ads.vrlib.utils.MatrixUtils;
import com.martin.ads.vrlib.utils.TextureUtils;

/**
 * @author lejun
 * @Description:
 */
public class RGBFilter extends PassThroughFilter {

    private Plane imagePlane;
    private RGBTexture rgbTexture;
    private byte[] rgba;
    private int width;
    private int height;


    public RGBFilter(Context context, byte[] rgba, int width, int height) {
        super(context);
        rgbTexture = new RGBTexture();
        imagePlane = new Plane(true);
        this.rgba = rgba;
        this.width = width;
        this.height = height;
    }

    @Override
    public void init() {
        super.init();
        rgbTexture.loadRGB(rgba, width, height);
    }

    @Override
    public void destroy() {
        super.destroy();
        rgbTexture.destroy();
    }

    @Override
    public void onDrawFrame(int textureId) {
        GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
        GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

        glPassThroughProgram.use();

        Matrix.setIdentityM(projectionMatrix, 0);

        imagePlane.uploadVerticesBuffer(glPassThroughProgram.getPositionHandle());
        imagePlane.uploadTexCoordinateBuffer(glPassThroughProgram.getTextureCoordinateHandle());
//        int textureFromBitmap = TextureUtils.getTextureFromBitmap(BitmapUtils.loadBitmapFromAssets(context, "imgs/hospot_logo.png"), new int[2]);
        TextureUtils.bindTexture2D(rgbTexture.getRGBTextureId(), GLES20.GL_TEXTURE0, glPassThroughProgram.getTextureSamplerHandle(), 0);
        MatrixUtils.updateProjectionWrap(100, 100, surfaceWidth, surfaceHeight, projectionMatrix);
        GLES20.glUniformMatrix4fv(glPassThroughProgram.getMVPMatrixHandle(), 1, false, projectionMatrix, 0);

        GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight);

        imagePlane.draw();
//        int textureFromBitmap = TextureUtils.getTextureFromBitmap(BitmapUtils.loadBitmapFromAssets(context, "imgs/hospot_logo.png"), new int[2]);
//        super.onDrawFrame(rgbTexture.getRGBTextureId());
    }
}
